package com.graduate.after.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.graduate.after.bean.*;
import com.graduate.after.mapper.HomeCategoryMapper;
import com.graduate.after.mapper.ShopCarInfoMapper;
import com.graduate.after.mapper.SlideShowMapper;
import com.graduate.after.service.ShopCarInfoService;
import com.graduate.after.utils.IdWorker;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class ShopCarInfoServiceImpl implements ShopCarInfoService {

    private static Logger log = Logger.getLogger(ShopCarInfoServiceImpl.class.getClass());

    @Autowired
    private ShopCarInfoMapper shopCarInfoMapper;

    @Autowired
    private HomeCategoryMapper homeCategoryMapper;

    @Autowired
    private SlideShowMapper slideShowMapper;

    @Autowired
    private AlipayClient alipayClient;


    @Override
    public String shopCarInfoInsert(String userName, Long shopIid) {

        //先查询是否有该信息，有则数量加一，无则新建
        ShopCarInfo shopCarInfo = shopCarInfoMapper.shopCarInfoSelect(userName, shopIid);
        if(shopCarInfo != null) {
            System.out.println("已有该信息，只需数量加一即可");
            shopCarInfoMapper.shopCarInfoUpdate(shopCarInfo.getId(),shopCarInfo.getShopCount()+1);
            return "One";
        }else{
            System.out.println("没有该信息，故新建信息");
            IdWorker idWorker = new IdWorker();
            long id = idWorker.nextId();
            // 雪花算法算出来的是19位数字,js数字最长为16位，故截去三位
            id = Long.parseLong(String.valueOf(id).substring(3));

            shopCarInfo = new ShopCarInfo();
            shopCarInfo.setId(id);
            shopCarInfo.setUserName(userName);
            shopCarInfo.setShopIid(shopIid);
            shopCarInfo.setShopCount(1);

            shopCarInfoMapper.shopCarInfoInsert(shopCarInfo);
            return "Two";
        }
    }

    @Override
    public List<ShopCarSingleInfo> shopCarAllSelect(String userName) {
        List list = new ArrayList();

        List<ShopCarInfo> shopCarInfos = shopCarInfoMapper.shopCarAllSelect(userName);
        Iterator<ShopCarInfo> iterator = shopCarInfos.iterator();

        while(iterator.hasNext()) {
            ShopCarSingleInfo shopCarSingleInfo = new ShopCarSingleInfo();
            ShopCarInfo next = iterator.next();
            shopCarSingleInfo.setShopCount(next.getShopCount());
            HomeCategory homeCategory = homeCategoryMapper.homeCateGoryByIid(next.getShopIid());

            shopCarSingleInfo.setIid(homeCategory.getId());
            shopCarSingleInfo.setImageUrl(homeCategory.getImageUrl());
            shopCarSingleInfo.setName(homeCategory.getName());
            shopCarSingleInfo.setRealPrice(homeCategory.getRealPrice());
            shopCarSingleInfo.setTitle(homeCategory.getTitle());
            shopCarSingleInfo.setChecked(false);
            list.add(shopCarSingleInfo);
        }
        return list;
    }

    @Override
    public Map orderInfoInsert(String list) throws AlipayApiException {

        String[] split = list.split("[|]");
        IdWorker idWorker = new IdWorker();
        long id = idWorker.nextId();
        // 雪花算法算出来的是19位数字,js数字最长为16位，故截去三位
        id = Long.parseLong(String.valueOf(id).substring(3));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String format = simpleDateFormat.format(new Date());

        //生成订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(id);
        orderInfo.setUserName(split[0]);
        orderInfo.setTotalMoney(Double.parseDouble(split[1]));
        orderInfo.setCategoryNum(Integer.parseInt(split[2]));
        orderInfo.setStatus("待付款");
        orderInfo.setDate(format);
        shopCarInfoMapper.orderInfoInsert(orderInfo);
        log.info("订单已生成");
        // 生成多个订单项
        for (int i = 3; i < split.length; i += 3) {
            OrderLineInfo orderLineInfo = new OrderLineInfo();
            IdWorker idWorkerLine = new IdWorker();
            long idLine = idWorkerLine.nextId();
            // 雪花算法算出来的是19位数字,js数字最长为16位，故截去三位
            idLine = Long.parseLong(String.valueOf(idLine).substring(3));
            orderLineInfo.setId(idLine);
            orderLineInfo.setIid(Long.parseLong(split[i]));
            orderLineInfo.setTotalPrice(Double.parseDouble(split[i+1]));
            orderLineInfo.setNum(Integer.parseInt(split[i+2]));
            orderLineInfo.setOrderId(id);
            shopCarInfoMapper.orderLineInfoInsert(orderLineInfo);
            log.info("第"+i/3+"个订单项已生成");

            // 删除购物车对应的信息
            shopCarInfoMapper.deleteShopCarSingleInfo(Long.parseLong(split[i]));
            log.info("第"+i/3+"个订单项所对应的购物车信息已删除");
        }


        // 生成支付宝订单,用于生成支付宝二维码
        String prefix = "wendao_";
        AliReturnPayBean aliBean = new AliReturnPayBean();
        aliBean.setApp_id("2016102700769671");
        aliBean.setOut_trade_no(prefix+id);
        aliBean.setSign("RSA2");
        aliBean.setTrade_status("未支付");
        aliBean.setTotal_amount(split[1]);
        aliBean.setSubject("文刀专卖店");

        String qrCode = createQrCode(aliBean);

        Map map = new HashMap();
        map.put("qrCode",qrCode);
        map.put("orderId",id);
        return map;
    }

    @Override
    public void changeStatus(Long id) {
        shopCarInfoMapper.orderInfoUpdate("待评价",id);
        log.info("id为"+id+"的订单状态已更改为已支付");
    }

    @Override
    public List OrderAllSelect(String userName, String type) {
        List sumList = new ArrayList();
        //查询订单
        List<OrderInfo> orderInfos = shopCarInfoMapper.orderAllSelect(userName, type);
        Iterator<OrderInfo> iterator = orderInfos.iterator();
        Integer parentCount = 1;
        while(iterator.hasNext()) {
            OrderInfo next = iterator.next();
            Long id = next.getId();
            String date = next.getDate().substring(0, 11);
            String status = next.getStatus();
            //查询订单项
            List<OrderLineInfo> orderLineInfos = shopCarInfoMapper.orderLineAllSelect(id);
            Iterator<OrderLineInfo> iterator1 = orderLineInfos.iterator();
            while (iterator1.hasNext()) {
                OrderLineInfo next1 = iterator1.next();
                Long iid = next1.getIid();
                List<SlideShow> slideShows = slideShowMapper.detailSlideShowSelect(iid);
                HomeCategory homeCategory = homeCategoryMapper.homeCateGoryByIid(iid);

                Map map = new HashMap();
                map.put("orderId",id);
                map.put("orderLineId",next1.getId());
                map.put("date",date);
                map.put("status",status);
                map.put("name",homeCategory.getName());
                map.put("totalMoney",next1.getTotalPrice());
                map.put("num",next1.getNum());
                map.put("slideShow",slideShows);
                sumList.add(map);
            }
        }

        return sumList;


        // 订单页树形展示则用下方代码
//        List sumList = new ArrayList();
//        //查询订单
//        List<OrderInfo> orderInfos = shopCarInfoMapper.orderAllSelect(userName, type);
//        Iterator<OrderInfo> iterator = orderInfos.iterator();
//        Integer parentCount = 1;
//        while(iterator.hasNext()) {
//            Map map = new HashMap();
//            OrderInfo next = iterator.next();
//            map.put("id",parentCount);
//            map.put("date",next.getDate());
//            map.put("totalMoney",next.getTotalMoney());
//            map.put("Num",next.getCategoryNum());
//            Long id = next.getId();
//            //查询订单项
//            List<OrderLineInfo> orderLineInfos = shopCarInfoMapper.orderLineAllSelect(id);
//            Iterator<OrderLineInfo> iterator1 = orderLineInfos.iterator();
//            List list1 = new ArrayList();
//            Integer childCount = 1;
//            while(iterator1.hasNext()) {
//                Map map1 = new HashMap();
//                OrderLineInfo next1 = iterator1.next();
//                map1.put("id",parentCount*10+childCount);
//                map1.put("totalPrice",next1.getTotalPrice());
//                map1.put("num",next1.getNum());
//                Long iid = next1.getIid();
//                HomeCategory homeCategory = homeCategoryMapper.homeCateGoryByIid(iid);
//                map1.put("name",homeCategory.getName());
//                map1.put("imageUrl",homeCategory.getImageUrl());
//                list1.add(map1);
//                childCount++;
//            }
//            map.put("children",list1);
//            sumList.add(map);
//            parentCount++;
//        }
//        return sumList;
    }

    @Override
    public Long refundOrderLine(Long orderId, Long orderLineId) {

        //先根据orderId进行查询，判断该订单的订单项个数，再进行分类处理
        OrderInfo orderInfo = shopCarInfoMapper.selectOrderById(orderId);
        Integer categoryNum = orderInfo.getCategoryNum();
        // 如果该订单里只有一个订单项，则直接修改订单状态即可，否则就需要新生成一个订单(订单时间不能变)来保存退款订单
        if(categoryNum == 1) {
            shopCarInfoMapper.orderInfoUpdate("已退款",orderId);
            return null;
        }else if(categoryNum >1){
            OrderLineInfo orderLineInfo = shopCarInfoMapper.selectOrderLineById(orderLineId);

            //生成新订单
            IdWorker idWorker = new IdWorker();
            long id = idWorker.nextId();
            // 雪花算法算出来的是19位数字,js数字最长为16位，故截去三位
            id = Long.parseLong(String.valueOf(id).substring(3));
            OrderInfo orderInfo1 = new OrderInfo();
            orderInfo1.setId(id);
            orderInfo1.setStatus("已退款");
            orderInfo1.setCategoryNum(1);
            orderInfo1.setUserName(orderInfo.getUserName());
            orderInfo1.setDate(orderInfo.getDate());
            orderInfo1.setTotalMoney(orderLineInfo.getTotalPrice());
            shopCarInfoMapper.orderInfoInsert(orderInfo1);

            //修改原订单
            double totalMoney = orderInfo.getTotalMoney() - orderLineInfo.getTotalPrice();
            categoryNum = categoryNum-1;
            shopCarInfoMapper.orderInfoUpdateMax(totalMoney,categoryNum,orderId);

            //修改订单项的所属
            shopCarInfoMapper.orderLineInfoUpdate(id,orderLineId);
            return id;
        }else {
            System.out.println("代码能执行到这里我直播跳楼");
            return null;
        }
    }

    public String createQrCode(AliReturnPayBean aliReturnPayBean) throws AlipayApiException {

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); //创建API对应的request类
        // 启动项目前更换新的内网穿透映射的url--->用natapp
        request.setNotifyUrl("http://w393eg.natappfree.cc/shopCar/call");
//        request.setReturnUrl("http://127.0.0.1:8081"); //想支付成功后跳转到该页面，出了点小问题，问题不大，在前端跳转路由一样
        request.setBizContent(JSON.toJSONString(aliReturnPayBean));
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return response.getQrCode();
        } else {
            System.out.println("调用失败");
        }
        return "";
    }
}
